package cn.xuexiluxian.open.admin.controller.personal;

import cn.hutool.core.util.StrUtil;
import cn.xuexiluxian.open.common.annotation.Log;
import cn.xuexiluxian.open.common.annotation.RepeatSubmit;
import cn.xuexiluxian.open.common.constant.Constants;
import cn.xuexiluxian.open.common.controller.BaseController;
import cn.xuexiluxian.open.common.entity.LoginUser;
import cn.xuexiluxian.open.common.enums.BusinessType;
import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.common.utils.AesUtil;
import cn.xuexiluxian.open.system.model.dto.SystemUserDTO;
import cn.xuexiluxian.open.system.model.dto.UpdateAvatarDTO;
import cn.xuexiluxian.open.system.model.dto.UpdatePasswordDTO;
import cn.xuexiluxian.open.system.model.entity.SystemMenu;
import cn.xuexiluxian.open.system.model.entity.SystemRole;
import cn.xuexiluxian.open.system.model.entity.SystemUnit;
import cn.xuexiluxian.open.system.model.entity.SystemUser;
import cn.xuexiluxian.open.system.model.vo.SystemRoleVO;
import cn.xuexiluxian.open.system.model.vo.SystemRouterVO;
import cn.xuexiluxian.open.system.service.ISystemMenuService;
import cn.xuexiluxian.open.system.service.ISystemRoleService;
import cn.xuexiluxian.open.system.service.ISystemUnitService;
import cn.xuexiluxian.open.system.service.ISystemUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 个人中心
 */
@Slf4j
@RestController
@RequestMapping("personal")
public class PersonalController extends BaseController {
    @Autowired
    private ISystemUserService systemUserService;
    @Autowired
    private ISystemRoleService systemRoleService;
    @Autowired
    private ISystemMenuService systemMenuService;
    @Autowired
    private ISystemUnitService systemUnitService;

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("getInfo")
    @Log(title = "个人中心", businessType = BusinessType.SELECT)
    public ResponseResult getInfo(){
        LoginUser currentUser = getCurrentUser();
        SystemUser systemUser = systemUserService.getById(currentUser.getId());
        BeanUtils.copyProperties(systemUser, currentUser);
        // 角色集合
        Set<SystemRoleVO> roles = new HashSet<>();
        // 权限集合
        Set<String> permissions = new HashSet<>();
        if (currentUser.isAdmin()) {
            roles.add(new SystemRoleVO("0", "超级管理员", Constants.SUPER_ADMIN_ROLE));
            permissions.add("*:*:*");
        } else {
            List<SystemRole> systemRoles = systemRoleService.selectListByUserId(currentUser.getId());
            for (int i = 0; i < systemRoles.size(); i++) {
                SystemRole item = systemRoles.get(i);
                roles.add(new SystemRoleVO(item.getId(), item.getRoleName(), item.getRolePerm()));
            }
            List<SystemMenu> systemMenus = systemMenuService.selectListByUserId(currentUser.getId());
            for (int i = 0; i < systemMenus.size(); i++) {
                SystemMenu item = systemMenus.get(i);
                permissions.add(item.getPerms());
            }
        }

        SystemUnit systemUnits = systemUnitService.getById(currentUser.getUnitId());

        Map<String, Object> data = new HashMap();
        data.put("userInfo", currentUser);
        data.put("units", systemUnits);
        data.put("roles", roles);
        data.put("permissions", permissions);
        return ResponseResult.ok(data);
    }

    @GetMapping("getRouters/{rolePerm}")
    @Log(title = "个人中心", businessType = BusinessType.SELECT)
    public ResponseResult getRouters(@PathVariable String rolePerm){
        List<SystemRouterVO> routers = systemMenuService.getRouters(rolePerm);
        return ResponseResult.ok(routers);
    }

    @GetMapping("getPermissions")
    @Log(title = "个人中心", businessType = BusinessType.SELECT)
    public ResponseResult getPermissions(){
        return ResponseResult.ok(getCurrentUser().getPermissions());
    }

    /**
     * 修改个人信息
     *
     * @param systemUserDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping(value = "updatePersonal")
    @Log(title = "个人中心", businessType = BusinessType.UPDATE)
    public ResponseResult updatePersonal(@RequestBody SystemUserDTO systemUserDTO) {
        if(systemUserDTO == null || StrUtil.isBlank(systemUserDTO.getId())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        if(StrUtil.isNotBlank(systemUserDTO.getPhone())) {
            SystemUser systemUser = systemUserService.selectOneByMobile(systemUserDTO.getPhone());
            if(!systemUser.getId().equals(systemUserDTO.getId())){
                return ResponseResult.error(ResultStatusCodeEnum.MOBILE_BINDED);
            }
        }
        SystemUser systemUser = new SystemUser();
        systemUser.setId(getCurrentUserId());
        systemUser.setRealName(systemUserDTO.getRealName());
        systemUser.setEmail(systemUserDTO.getEmail());
        systemUser.setPhone(systemUserDTO.getPhone());
        systemUser.setGender(systemUserDTO.getGender());
        systemUser.setAvatar(systemUserDTO.getAvatar());
        boolean b = systemUserService.updateById(systemUser);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 修改密码
     *
     * @return
     */
    @RepeatSubmit
    @PostMapping(value = "updatePassword")
    @Log(title = "个人中心", businessType = BusinessType.UPDATE)
    public ResponseResult updatePassword(@RequestBody UpdatePasswordDTO updatePasswordDTO) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(StrUtil.isBlank(updatePasswordDTO.getOldPassword()) || StrUtil.isBlank(updatePasswordDTO.getNewPassword())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        String userId = getCurrentUserId();
        SystemUser systemUser = systemUserService.getById(userId);

        String oldPassword = AesUtil.decrypt(updatePasswordDTO.getOldPassword());
        String newPassword = AesUtil.decrypt(updatePasswordDTO.getNewPassword());

        boolean matches = passwordEncoder.matches(oldPassword, systemUser.getPassword());
        if (!matches) {
            return ResponseResult.error("旧密码不正确");
        }
        SystemUser updateUser = new SystemUser();
        updateUser.setId(userId);
        updateUser.setPassword(passwordEncoder.encode(newPassword));
        boolean b = systemUserService.updateById(updateUser);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 修改头像
     * @param updateAvatarDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping(value = "updateAvatar")
    @Log(title = "个人中心", businessType = BusinessType.UPDATE)
    public ResponseResult updateAvatar(@RequestBody UpdateAvatarDTO updateAvatarDTO) {
        if(StrUtil.isBlank(updateAvatarDTO.getId()) || StrUtil.isBlank(updateAvatarDTO.getAvatar())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        String userId = getCurrentUserId();
        SystemUser updateUser = new SystemUser();
        updateUser.setId(userId);
        updateUser.setAvatar(updateAvatarDTO.getAvatar());
        boolean b = systemUserService.updateById(updateUser);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }
}
